package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.service.goods.SkuSearchService;
import com.qingcheng.util.WebUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * Welcome to the most Amazing IntelliJ IIIDEA.
 * Creat0r: ^_^ fffantianxing ^_^
 * Date: 2019-07-08
 * Time: 12:27
 */
@Controller
public class SearchController {

    @Reference
    private SkuSearchService skuSearchService;

    @GetMapping("search")
    public String search(Model model, @RequestParam Map<String, String> searchMap) throws Exception {

        StringBuffer url = new StringBuffer("/search.do?");

        if (searchMap.get("currentPage") == null) {//当参数中没有currentPage时，将currentPage设置为1
            searchMap.put("currentPage", "1");
//            url.append("&currentPage="+searchMap.get("currentPage"));
        }

        String sort = searchMap.get("sort");
        if (sort == null) {//如果没有排序，将排序设置为空，防止空指针
            searchMap.put("sort","");
        }
        String sortOrder = searchMap.get("sortOrder");
        if (sortOrder == null) {
            searchMap.put("sortOrder","DESC");
        }

        Map result = skuSearchService.skuSearch(searchMap);//向request域中添加result
        model.addAttribute("result", result);

        Long totalPage = (Long) result.get("totalPage");

        //设置分页栏
        int startPage = 1;//开始页
        int endPage = totalPage.intValue();//结束页
        Integer currentPage = Integer.parseInt(searchMap.get("currentPage"));
        if (totalPage > 5) {
            startPage = currentPage - 2;
            if (startPage < 1) {
                startPage = 1;
            }
            endPage = currentPage + 2;
            if (endPage < 5) {
                endPage = 5;
            }
            if (endPage > totalPage) {
                endPage = totalPage.intValue();
            }
        }

        for (String key : searchMap.keySet()) {

            if (key.equals("keywords")) {
                url.append(key + "=" + searchMap.get(key));
            } else {
                url.append("&" + key + "=" + searchMap.get(key));
            }
        }

        model.addAttribute("currentPage", currentPage);
        model.addAttribute("url", url);
        model.addAttribute("searchMap", searchMap);
        model.addAttribute("startPage", startPage);
        model.addAttribute("endPage", endPage);

        return "search";
    }
}
